from django.contrib import admin
from .models import Category, Product, Review, Tag, ProductTag


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'description', 'created_at', 'products_count']
    search_fields = ['name', 'description']
    list_filter = ['created_at']
    ordering = ['-created_at']

    def products_count(self, obj):
        return obj.products.count()
    products_count.short_description = '产品数量'


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['name', 'category', 'price', 'status', 'stock', 'created_by', 'created_at']
    list_filter = ['status', 'category', 'created_at', 'created_by']
    search_fields = ['name', 'description', 'category__name']
    list_editable = ['status', 'price', 'stock']
    ordering = ['-created_at']
    raw_id_fields = ['created_by']

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'category', 'status')
        }),
        ('价格和库存', {
            'fields': ('price', 'stock')
        }),
        ('其他', {
            'fields': ('image', 'created_by'),
            'classes': ('collapse',)
        })
    )

    def save_model(self, request, obj, form, change):
        if not change:  # 新创建的对象
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
    list_display = ['product', 'reviewer', 'rating', 'comment_preview', 'created_at']
    list_filter = ['rating', 'created_at', 'product__category']
    search_fields = ['product__name', 'reviewer__username', 'comment']
    ordering = ['-created_at']
    raw_id_fields = ['product', 'reviewer']

    def comment_preview(self, obj):
        return obj.comment[:50] + '...' if len(obj.comment) > 50 else obj.comment
    comment_preview.short_description = '评论预览'


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ['name', 'color', 'usage_count']
    search_fields = ['name']
    ordering = ['name']

    def usage_count(self, obj):
        return obj.producttag_set.count()
    usage_count.short_description = '使用次数'


class ProductTagInline(admin.TabularInline):
    model = ProductTag
    extra = 1
    raw_id_fields = ['tag', 'added_by']


# 在Product管理页面中添加标签内联编辑
# ProductAdmin.inlines = [ProductTagInline]


@admin.register(ProductTag)
class ProductTagAdmin(admin.ModelAdmin):
    list_display = ['product', 'tag', 'added_by', 'added_at']
    list_filter = ['tag', 'added_at']
    search_fields = ['product__name', 'tag__name', 'added_by__username']
    ordering = ['-added_at']
    raw_id_fields = ['product', 'tag', 'added_by']
